var express = require('express');
var util = require('util');
var path = require('path');
var fs = require('fs');
var wechat = require('wechat');
var url = require('url');
var app = express();

// wechat
var config = {
  token: 'pengloo53',
  appid: 'wx27ebfbeddddaea30',
};
var count = 0;
app.use('/', wechat(config, function (req, res, next) {
  // 微信输入信息都在req.weixin上
  var message = req.weixin;
  var username = message.FromUserName;
  var Content = (typeof(message.Content) == 'undefined')?'try again.':message.Content;
  console.log(username + ": " + Content);
  var filePath = '/.tasks/.' + username;
  var file = path.join(process.cwd(), filePath);
  var content = '';

  if(Content.substring(0,2) == 'ls'){
    list(file, function(replys){
      res.reply(replys);
    });
  }else if(Content.substring(0,3) == 'add'){
    content = Content.substring(3).trim();
    add(file,content);
  }else if(Content.substring(0,3) == 'del'){
    content = Content.substring(3).trim();
    var delId = parseInt(content);
    delData(file, delId);
  }else if(Content.substring(0,1) == '?' || Content.substring(0,1) == '？'){
    res.reply("『代办事项』小应用\n用法：\n1. 添加一条代办事项，输入`add message`；\n2. 添加多条，输入`add message1 message2`；\n3. 输入`del id`删除指定事项；\n4. 输入`ls`查看所有代办事项。\n5. 输入`clear`清空待办事项列表。 ");
  }else if(Content.substring(0,5)== 'clear'){
    clear(file);
  }else{
    res.reply("尝试输入一个问号看看...");
  }

// 清空
  function clear(file){
    initData(file,function(tasks){
      tasks = [];
      storeData(tasks,file);
      res.reply("清空完成");
    });
  }

// 删除
  function delData(file,delId){
    initData(file, function(tasks){
      if (isNaN(delId)){
        res.reply("请规范输入，del后接要删除的数字，eg. del 3");
      }else if(!tasks[delId]){
        res.reply("输入的del id不存在");
      }else{
        var delItem = tasks.splice(delId , 1);
        storeData(tasks, file);
        res.reply("第" + delId + "条内容:「" + delItem + "」删除成功，输入ls查看");
      }
    });
  }

// 初始化数据，将文件写入内存中
  function initData(file, callback){
    fs.stat(file, function(err, stats){
      if (err){
        callback([]);
      }else{
        var tasks = [];
        fs.readFile(file, 'utf8', function (err, results){
          if (err){
            throw err;
          }
          var results = results.toString();
          tasks = JSON.parse(results || '[]');
          callback(tasks);
        });
      }
    });
  }

// 列出todo-list
  function list(file,callback){
    var replyMessage = '';
    initData(file, function(results){
      for(var i=0 ; i < results.length ; i++){
        var item = "「" + i + "」"+ results[i] + "\n";
        replyMessage += item;
      }
      if(replyMessage == ''){
        callback('请使用add+Message添加一条代办事项');
      }else{
        callback(replyMessage);
      }
    });
  }

  // 保存todo-list
  function storeData(tasks, file){
    fs.writeFile(file, JSON.stringify(tasks), 'utf8', function(err){
      if (err){
        throw err;
      }
      console.log("store success.");
    });
  }

  // 添加todo-list
  function add (file, content){
    initData(file, function (tasks){
      if(content == ''){
        res.reply('添加点内容呗');
      }else{
        var contentArr = content.split(' ');
        for (var i = 0; i < contentArr.length; i++) {
          if(contentArr[i] == ''){
            continue;
          }
          tasks.push(contentArr[i].trim());
        }
        storeData(tasks, file);
        res.reply("「 " + content + "」, 添加成功. 输入ls查看 ");
      }
    });
  }
}));

app.listen(9090);
console.log('Server is start at port 9090');
